package common;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class RealmConf
{
	static private RealmConf _self;
	static public String _dbHost = "127.0.0.1", _dbUser = "root",_dbPass = "",_dbName = "anc_realm",_interPass = "ancestra";
	static public boolean _debug = false,_sendPolicy = false,_localhostLoopback = true,_log = true,_activeSubscribe = false;
	static public short _realmPort = 443,_interPort = 5000;
	static public byte _gmLevelAutoSubscribe = 1;
	
	/**
	 * Link the new RealmConf to the class, as static parameter.
	 */
	public RealmConf()
	{
		if(_self != null)return;
		_self = this;
	}
	
	/**
	 * Load a specified configuration file
	 * @param file : The file to load
	 * @return a RealmConfg Object
	 */
	public static RealmConf loadConfigFile(String file)
	{
		//Initialize _self parameter
		new RealmConf();
		try {
			BufferedReader config = new BufferedReader(new FileReader(file));
			String line = "";
			while ((line=config.readLine())!=null)
			{
				if(line.equals(""))continue;
				if(line.startsWith("#"))continue;
				
				line = line.split("#")[0];
				if(line.split("=").length == 1) continue ;
				String param = line.split("=")[0].trim();
				String value = line.split("=")[1].trim();
				
				if(param.equalsIgnoreCase("LOG"))
					_log = value.equalsIgnoreCase("true");
				else if(param.equalsIgnoreCase("DEBUG"))
					_debug = value.equalsIgnoreCase("true");
				else if(param.equalsIgnoreCase("SEND_POLICY"))
					_sendPolicy = value.equalsIgnoreCase("true");
				else if(param.equalsIgnoreCase("LOCALHOST_LOOPBACK"))
					_localhostLoopback = value.equalsIgnoreCase("true");
				else if(param.equalsIgnoreCase("ACTIVE_SUBSCRIBE"))
					_activeSubscribe = value.equalsIgnoreCase("true");
				else if(param.equalsIgnoreCase("REALM_PORT"))
				{
					try { _realmPort = Short.parseShort(value);}
					catch(NumberFormatException e){continue;};
				}
				else if(param.equalsIgnoreCase("INTERSERVER_PORT"))
				{
					try { _interPort = Short.parseShort(value);}
					catch(NumberFormatException e){continue;};
				}
				else if(param.equalsIgnoreCase("GMLVL_AUTOSUBSCRIBE"))
				{
					try {_gmLevelAutoSubscribe = Byte.parseByte(value);}
					catch(NumberFormatException e){continue;};
				}
				else if(param.equalsIgnoreCase("INTERSERVER_PASS"))
					_interPass = value;
				else if(param.equalsIgnoreCase("DB_HOST"))
					_dbHost = value;
				else if(param.equalsIgnoreCase("DB_USER"))
					_dbUser = value;
				else if(param.equalsIgnoreCase("DB_PASS"))
					_dbPass = value;
				else if(param.equalsIgnoreCase("DB_NAME"))
					_dbName = value;
			}
			
			System.out.println("Ok !");
		}catch(IOException ioe)
		{
			System.out.println("Error while reading configuration file");
			System.out.println("Exiting server");
			System.exit(0);
		}
		
		return _self;
	}
}
